<template>
  <page-container :title="route.meta.title">
    <SearchTable
      ref="tableRef"
      :table-list-api="tableListApi"
      :columns="columns"
      :show-selection="true"
      :convert-from-response="res => res.data"
    >
      <template #tableBtns>
        <a-button v-action:create type="primary" @click="handleCreating">新建</a-button>
      </template>
    </SearchTable>
    <FormDialog
      v-if="pageType === PAGE_TYPE.CREATING || pageType === PAGE_TYPE.EDITING"
      ref="createForm"
      :mode="pageType"
      :form-data="formData"
      :items="columns"
      @ok="handleOk"
      @cancel="handleCancel"
    />
  </page-container>
</template>

<script setup lang="tsx">
import { useRoute } from 'vue-router';
import SearchTable from '@/components/SearchTable';
import useTablePage, { PAGE_TYPE } from '@/hooks/useTablePage';
import { createThirdadplatform, deleteThirdadplatform, modifyThirdadplatform } from '@/api/thirdplatform';
import { Modal } from 'ant-design-vue';
import type { IColumn, IRow } from '@/types';

const { pageType } = useTablePage();
const route = useRoute();
const tableListApi = '/v1/thirdadplatform/list';
const tableRef = ref();

const columns: IColumn[] = [
  {
    title: '序号',
    dataIndex: 'id',
    readonly: true,
  },
  {
    title: '广告平台名称',
    dataIndex: 'platform_name',
    searchable: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: 240,
    fixed: 'right',
    customRender: ({ record }) => {
      // TODO: 按钮需要配置权限
      const btns = [
        <a-button type="link" onClick={() => handleEditing(record)}>
          编辑
        </a-button>,
        <a-button type="link" danger onClick={() => handleDeleting(record)}>
          删除
        </a-button>,
      ];
      return btns;
    },
  },
];

const handleOk = async (state: any) => {
  console.log('🚀 ~ handleOk ~ state:', state);
  if (pageType.value === PAGE_TYPE.CREATING) {
    await createThirdadplatform(state);
  } else {
    await modifyThirdadplatform(state);
  }

  pageType.value = null;
  tableRef.value.refreshTable();
};
const handleCancel = () => {
  pageType.value = null;
};
const handleCreating = () => {
  pageType.value = PAGE_TYPE.CREATING;
};
const formData = reactive({});
const handleEditing = (record: Record<string, unknown>) => {
  console.log('🚀 ~ handleEditing ~ record:', record);
  Object.assign(formData, record);
  pageType.value = PAGE_TYPE.EDITING;
};

const handleDeleting = (record: IRow) => {
  Modal.confirm({
    title: '警告',
    content: `确认删除 ${record.platform_name} 吗?`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return deleteThirdadplatform(record.id).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};
</script>
